<template>
    <SavePage v-loading="loading" :title="title" width="1330px">
        <template v-if="type !== 'detail'" slot="buttons">
            <BaseButton :loading="submitLoading" @click="handleSubmit">保存</BaseButton>
        </template>
        <template slot="body">
            <BaseForm ref="form" label-position="right" :fields="fields" :text-model="textModel" :data="form" size="medium" @updateValue="updateEvent">
            </BaseForm>
        </template>
    </SavePage>
</template>

<script>
import BaseForm from '@/components/BaseForm'
import { {{ modelName }} } from '@/models'

export default {
    name: '{{ modelName }}Add',
    components: {
        BaseForm
    },
    data() {
        return {
            type: 'add',
            title: '新增xxxx',
            id: '',
            loading: false,
            submitLoading: false,
            textModel: false,
            allDisabled: false,
            model: new {{ modelName }}(),
            form: {},
            fields: [
                {
                    label: '基础信息',
                    children: [
                        {
                            options: [],
                            key: 'direction',
                            valueKey: 'label',
                            label: '方向',
                            type: 'normal-select',
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        }
                    ]
                },
                {
                    label: '地理信息',
                    children: [
                        {
                            key: 'startingPointStake',
                            label: '起点桩号',
                            type: 'stake'
                        },
                        {
                            key: 'terminalPointStake',
                            label: '终点桩号',
                            type: 'stake'
                        },
                        {
                            key: 'startingLngAndLat',
                            label: '起点经纬度',
                            type: 'location',
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            key: 'terminalLngAndLat',
                            label: '终点经纬度',
                            type: 'location',
                            rules: [{ required: true, message: '必填项', trigger: ['change'] }]
                        },
                        {
                            key: 'empty1',
                            type: 'empty'
                        },
                        {
                            key: 'empty2',
                            type: 'empty'
                        }
                    ]
                },
            ],
            lineNameList: []
        }
    },
    created() {
        this.init()
        this.getHighwayList()
        this.getManagementOfficeList()
    },
    methods: {
        updateEvent(data) {
            // data.key
        },
        async init() {
            this.type = this.$route.query.type
            this.id = this.$route.query.id
            if (this.type === 'edit') {
                this.title = '编辑xxxx'
                this.addFormItem()
                const res = await this.getDetail()
                res.startingPointStake = res.startingPointStake.replace('K', '').split('+')
                res.terminalPointStake = res.terminalPointStake.replace('K', '').split('+')
                res.updateUserName = res.updateUserName || '-'
                this.form = res
            } else if (this.type === 'detail') {
                this.title = this.$route.query.code + '详情'
                this.textModel = true
                this.addFormItem()
                this.form = await this.getDetail()
            } else {
                this.title = '新增xxxx'
                console.log('新增')
            }
        },
        // 获取线路名称列表，作为下拉选项
        getLineNameList(highwayId) {
            this.model.getNameList({ highwayId, id: this.id || null }).then((res) => {
                this.lineNameList = (res || []).map((item) => {
                    return {
                        label: item.name,
                        value: item.code
                    }
                })
                this.$set(this.fields[0].children[1], 'options', this.lineNameList)
            })
        },
        // 获取公路列表，作为下拉选项
        getHighwayList() {
            this.lineHighwayModel.getList({}, { pageNo: 1, pageSize: 10000 }).then((res) => {
                const list = (res.list || []).map((item) => {
                    return {
                        label: item.name,
                        value: item.id
                    }
                })
                list.length > 0 && this.$set(this.fields[0].children[0], 'options', list)
            })
        },
        // 获取管理处列表，作为下拉选项
        getManagementOfficeList() {
            this.managementOfficeModel.getList({}, { pageNo: 1, pageSize: 10000 }).then((res) => {
                const list = (res.list || []).map((item) => {
                    return {
                        value: item.id,
                        label: item.name
                    }
                })
                list.length > 0 && this.$set(this.fields[2].children[0], 'options', list)
            })
        },
        // 获取监控中心列表，作为下拉选项
        getSurveillanceCenterList(id) {
            this.surveillanceCenterModel.getList({ managementId: id }, { pageNo: 1, pageSize: 10000 }).then((res) => {
                const list = (res.list || []).map((item) => {
                    return {
                        label: item.name,
                        value: item.id
                    }
                })
                this.$set(this.fields[2].children[1], 'options', list)
            })
        },
        addFormItem() {
            this.fields.push({
                label: '数据维护记录',
                children: [
                    {
                        key: 'updateUserName',
                        type: 'input',
                        label: '最近修改人',
                        disableDefault: true
                    },
                    {
                        key: 'updateTime',
                        type: 'input',
                        label: '最近修改时间',
                        disableDefault: true
                    },
                    {
                        key: 'empty',
                        type: 'empty'
                    }
                ]
            })
        },
        getDetail() {
            this.loading = true
            return this.model.detail({ id: this.id }).finally(() => {
                this.loading = false
            })
        },
        handleSubmit() {
            this.submitLoading = true
            this.$refs['form'].validate((valid, res) => {
                if (valid) {
                    console.log('这是你刚提交的数据', res)
                    const startingPointStake = `K${res.startingPointStake[0]}+${res.startingPointStake[1]}`
                    const terminalPointStake = `K${res.terminalPointStake[0]}+${res.terminalPointStake[1]}`
                    //  后端需要把线路的名称和code都传过去
                    const name = (this.lineNameList.find((item) => item.value === res.code) || {}).label
                    const data = {
                        ...res,
                        name,
                        startingPointStake,
                        terminalPointStake
                    }
                    this.id && (data.id = this.id)
                    this.model
                        .saveOrUpdate(data)
                        .then(() => {
                            this.$message({
                                type: 'success',
                                message: '操作成功！',
                                duration: 500,
                                onClose: () => {
                                    this.$router.go(-1)
                                }
                            })
                        })
                        .finally(() => {
                            this.submitLoading = false
                        })
                } else {
                    this.submitLoading = false
                    this.$message.error('校验失败！')
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped></style>
